<template>
  <!-- 考试须知 -->
  <div class="box" v-if="isBeforeExam">
    <el-descriptions :column="1" size="large">
      <template #title>
        <el-text tag="b" type="danger" style="font-size: 30px">请输入问卷动态答题密码</el-text>
      </template>
      <el-descriptions-item>
        <template #label>
          <el-text tag="b" size="large">请输入问卷动态答题密码</el-text>
        </template>
        <el-input v-model.trim="dataSource.password" placeholder="请输入密码" maxLength="50" />
      </el-descriptions-item>
    </el-descriptions>
    <el-button type="primary" @click="startExam"> 开始考试 </el-button>
  </div>
  <div class="paper-main" v-if="!isBeforeExam">
    <!-- 问卷页面 -->
    <div class="paper-header">
      {{ dataSource.paperName }}{{ dataSource.openType === 1 ? '(预览模式)' : '(答题模式)' }}
    </div>
    <!-- 试题内容 -->
    <div ref="paperContent" class="paper-content">
      <div class="subject" v-for="(item, idx) in convertDataList" :key="item.name">
        <div class="subject-title">
          <h2>{{ idx + 1 }}.{{ item.name }}</h2
          ><spn>（共 {{ item.count }} 题）</spn>
        </div>
        <el-form ref="formRef" :model="item" :rules="formRules" :inline="true">
          <el-card
            class="box-card"
            v-for="(sub, index) in item.childs"
            :id="'paperContent' + sub.id"
            :key="sub.id"
          >
            <div class="clearfix">
              <el-tag effect="dark"> {{ index + 1 }} </el-tag>
              <span>{{ sub.questionContent }}</span>
            </div>

            <!-- 单选题选项 -->
            <el-radio-group
              v-if="sub.optionType === 1"
              v-model="sub.answerContent"
              :style="{
                'min-height': '80px'
              }"
            >
              <el-radio
                v-for="o in sub.optionList"
                :label="o.optionKey"
                :key="o.optionKey"
                class="answer-radio"
                :disabled="dataSource.openType === 1"
              >
                {{ o.optionKey }}. {{ o.optionContent }}
              </el-radio>
            </el-radio-group>
            <!-- 多选题选项 -->
            <el-checkbox-group
              v-if="sub.optionType === 2"
              v-model="sub.answerList"
              :style="{
                'min-height': '80px'
              }"
              @change="
              (val) => {
                sub.answerContent = val.sort((a:string, b:string) => {
                  // 将字符转换为ASCII值进行比较
                  return a.charCodeAt(0) - b.charCodeAt(0)
                }).join(',')
              }
            "
            >
              <el-checkbox
                v-for="o in sub.optionList"
                :label="o.optionKey"
                :key="o.optionKey"
                class="answer-checkbox"
                :disabled="dataSource.openType === 1"
              >
                {{ o.optionKey }}.{{ o.optionContent }}
              </el-checkbox>
            </el-checkbox-group>
            <!-- 判断题选项 -->
            <el-radio-group v-if="sub.optionType === 3" v-model="sub.answerContent">
              <el-radio label="2" class="answer-radio" :disabled="dataSource.openType === 1"
                >对</el-radio
              >
              <el-radio label="1" class="answer-radio" :disabled="dataSource.openType === 1"
                >错</el-radio
              >
            </el-radio-group>
            <!-- 简答题选项 -->
            <el-input
              v-if="sub.optionType === 4"
              type="textarea"
              v-model="sub.answerContent"
              resize="none"
              maxlength="2000"
              :disabled="dataSource.openType === 1"
            />
            <div v-if="dataSource.openType !== 3" class="subject-remark">
              <div class="item">
                <span class="title">试题解析：</span>
                <span>{{ sub.analysis }}</span>
              </div>
              <div class="item" v-if="sub.optionType === 1 || sub.optionType === 2">
                <span class="title">选项解析：</span>
                <template v-for="option in sub.optionList" :key="option.id">
                  <span v-if="option.optionAnalysis">
                    选项{{ option.optionKey }}: {{ option.optionAnalysis }};&nbsp;
                  </span>
                </template>
              </div>
            </div>
          </el-card>
        </el-form>
      </div>
    </div>
    <div class="paper-footer">
      <el-button
        type="success"
        @click="btnClick"
        v-if="dataSource.openType === 3"
        :disabled="formLoading"
        class="w-[200px]"
      >
        交卷
      </el-button>
    </div>
  </div>
</template>
<script setup lang="ts" name="previewPaper">
import './previewPaperStyle.css'
const message = useMessage() // 消息弹窗
const route = useRoute()
const router = useRouter() // 路由对象
const isBeforeExam = ref(true) // 考试须知是否展示
const formRules = reactive({})
//数据源
const dataSource = ref({
  password: '', //假的输入密码
  paperName: '', //问卷名称
  openType: undefined
})
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

// 先定义题型映射
const typeMap = {
  1: { name: '单选题', code: 'Single' },
  2: { name: '多选题', code: 'Multiple' },
  3: { name: '判断题', code: 'Judgment' },
  4: { name: '简答题', code: 'Answer' }
}

// 初始化 convertDataList
const convertDataList = ref(
  Object.values(typeMap).map(({ name, code }) => ({
    name,
    code,
    count: 0,
    childs: []
  }))
)

// 开始考试
const startExam = async () => {
  // 获取数据
  getExam()
  // 展示问卷
  isBeforeExam.value = false
}

// 组装数据
const getExam = () => {
  const saved = window.localStorage.getItem('questionList')
  const data = saved ? JSON.parse(saved) : []
  // 遍历原始数据
  data.forEach((item) => {
    const target = convertDataList.value.find((v) => v.code === typeMap[item.optionType]?.code)
    if (target) {
      target.count++ // 题数累加
      target.childs.push(item) // 把当前题目塞进 childs
    }
  })
}

// 交卷
const btnClick = async () => {
  // 提交请求
  try {
    let unAnswerNum = 0

    convertDataList.value.forEach((item: Array<Object>) => {
      item.childs.forEach((it) => {
        if (it.answerContent === null || it.answerContent === '' || it.answerContent === undefined)
          unAnswerNum++
      })
    })
    // 二次确认
    if (unAnswerNum > 0) {
      await message.confirm(
        `当前还有 ${unAnswerNum} 道题未作答，问卷提交后将无法再次作答，是否继续提交?`
      )
    } else {
      await message.confirm('确定交卷吗?交卷后将关闭当前页面不可再次答题,请谨慎操作!')
    }
    formLoading.value = true
    message.success('交卷成功')
    setTimeout(function () {
      router.push({ path: '/paper-close' })
    }, 100) // 3000 毫秒等于 3 秒
  } finally {
    formLoading.value = false
  }
}

onMounted(() => {
  dataSource.value.paperName = route.query.paperName
  dataSource.value.openType = Number(route.query.openType)
})
</script>
<style scoped>
/* 考前须知页面样式,设置 body 和 HTML 为 100% 高度，确保页面铺满整个窗口 */
body,
html {
  height: 100%;
  margin: 0;
  background-color: #e9e6e6;
}

.box {
  position: relative;
  top: 50%;
  left: 50%;
  display: flex;
  max-width: 600px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  transform: translate(-50%, -50%);
  flex-direction: column;
}
</style>
